<?php

namespace app\controller\crm;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;
use think\facade\Validate;

/**
 * 合同审核管理
 */
class Contract extends BaseController
{
    /**
     * 获取待审核订单列表
     */
    public function pendingList()
    {
        $params = Request::param();
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 20;
        $customerName = $params['customer_name'] ?? '';

        $query = Db::name('crm_order')
            ->alias('o')
            ->field('o.id, o.order_no, o.customer_name, o.contract_no, o.total_amount, o.approval_status, o.create_time, c.name as customer_name_full')
            ->leftJoin('crm_customer c', 'o.customer_id = c.id')
            ->leftJoin('crm_contract_archive ca', 'o.id = ca.order_id')
            ->where('o.delete_time', 0)
            ->where('o.approval_status', 'in', [0, 1])  // 待审核或审核中
            ->where('ca.id', 'null');  // 未归档的订单

        if ($customerName) {
            $query->where('o.customer_name', 'like', '%' . $customerName . '%');
        }

        $total = $query->count();
        $list = $query->order('o.create_time', 'desc')
            ->page($page, $limit)
            ->select();

        return $this->paginate($list ? $list->toArray() : [], $total, (int)$page, (int)$limit);
    }

    /**
     * 上传合同附件
     */
    public function upload()
    {
        $params = Request::param();

        // 参数验证
        $validate = Validate::rule([
            'order_id|订单ID' => 'require|number',
            'contract_no|合同编号' => 'require',
            'contract_files|合同文件' => 'require'
        ]);

        if (!$validate->check($params)) {
            return $this->error($validate->getError());
        }

        // 检查订单是否存在
        $order = Db::name('crm_order')->where('id', $params['order_id'])->find();
        if (!$order) {
            return $this->error('订单不存在');
        }

        // 检查是否已存在归档记录
        $existingArchive = Db::name('crm_contract_archive')->where('order_id', $params['order_id'])->find();
        if ($existingArchive) {
            return $this->error('合同已归档');
        }

        $data = [
            'order_id' => $params['order_id'],
            'contract_no' => $params['contract_no'],
            'contract_start_date' => isset($params['contract_start_date']) ? strtotime($params['contract_start_date']) : null,
            'contract_end_date' => isset($params['contract_end_date']) ? strtotime($params['contract_end_date']) : null,
            'contract_files' => json_encode($params['contract_files']),
            'archive_status' => 0,  // 未归档
            'submitter_id' => $this->getUserId(),
            'create_time' => time(),
            'update_time' => time()
        ];

        $id = Db::name('crm_contract_archive')->insertGetId($data);

        if ($id) {
            // 更新订单的合同编号
            Db::name('crm_order')->where('id', $params['order_id'])->update([
                'contract_no' => $params['contract_no'],
                'contract_start_date' => $data['contract_start_date'],
                'contract_end_date' => $data['contract_end_date'],
                'update_time' => time()
            ]);

            return $this->success(['id' => $id], '上传成功');
        }

        return $this->error('上传失败');
    }

    /**
     * 合同审核通过
     */
    public function approve()
    {
        $orderId = Request::param('order_id');
        if (!$orderId) {
            return $this->error('参数错误');
        }

        $userId = $this->getUserId();
        if (!$userId) {
            return $this->error('未登录或登录已过期', 401);
        }

        $remark = Request::param('remark', '');

        // 检查合同归档记录是否存在
        $contractArchive = Db::name('crm_contract_archive')->where('order_id', $orderId)->find();
        if (!$contractArchive) {
            return $this->error('合同未归档');
        }

        // 检查是否有财务审核记录
        $hasFinanceRecord = Db::name('crm_finance_record')
            ->where('order_id', $orderId)
            ->where('verification_status', 1)
            ->count() > 0;

        // 如果财务审核未通过，则不能完成合同审核
        if (!$hasFinanceRecord) {
            return $this->error('财务审核未通过，无法完成合同审核');
        }

        // 更新合同归档状态
        Db::name('crm_contract_archive')->where('order_id', $orderId)->update([
            'archive_status' => 1,  // 已归档
            'reviewer_id' => $userId,
            'review_time' => time(),
            'review_remark' => $remark,
            'update_time' => time()
        ]);

        // 生成工单
        $this->generateWorkOrder($orderId);

        return $this->success([], '审核通过');
    }

    /**
     * 合同审核驳回
     */
    public function reject()
    {
        $orderId = Request::param('order_id');
        if (!$orderId) {
            return $this->error('参数错误');
        }

        $userId = $this->getUserId();
        if (!$userId) {
            return $this->error('未登录或登录已过期', 401);
        }

        $remark = Request::param('remark');
        if (!$remark) {
            return $this->error('请填写驳回理由');
        }

        // 检查合同归档记录是否存在
        $contractArchive = Db::name('crm_contract_archive')->where('order_id', $orderId)->find();
        if (!$contractArchive) {
            return $this->error('合同未归档');
        }

        // 更新合同归档状态
        Db::name('crm_contract_archive')->where('order_id', $orderId)->update([
            'archive_status' => 2,  // 审核驳回
            'reviewer_id' => $userId,
            'review_time' => time(),
            'review_remark' => $remark,
            'update_time' => time()
        ]);

        // 更新订单状态
        Db::name('crm_order')->where('id', $orderId)->update([
            'approval_status' => 3,  // 审核拒绝
            'update_time' => time()
        ]);

        return $this->success([], '审核驳回');
    }

    /**
     * 获取合同归档详情
     */
    public function detail()
    {
        $orderId = Request::param('order_id');
        if (!$orderId) {
            return $this->error('参数错误');
        }

        $contractArchive = Db::name('crm_contract_archive')
            ->alias('ca')
            ->field('ca.*, u1.name as submitter_name, u2.name as reviewer_name')
            ->leftJoin('admin u1', 'ca.submitter_id = u1.id')
            ->leftJoin('admin u2', 'ca.reviewer_id = u2.id')
            ->where('ca.order_id', $orderId)
            ->find();

        if (!$contractArchive) {
            return $this->error('合同归档记录不存在');
        }

        // 解析合同文件
        $contractArchive['contract_files'] = json_decode($contractArchive['contract_files'], true) ?: [];

        return $this->success($contractArchive);
    }

    /**
     * 获取合同归档列表
     */
    public function list()
    {
        $params = Request::param();
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 20;
        $customerName = $params['customer_name'] ?? '';
        $status = $params['status'] ?? '';

        $query = Db::name('crm_contract_archive')
            ->alias('ca')
            ->field('ca.*, o.order_no, o.customer_name, u1.name as submitter_name, u2.name as reviewer_name')
            ->leftJoin('crm_order o', 'ca.order_id = o.id')
            ->leftJoin('admin u1', 'ca.submitter_id = u1.id')
            ->leftJoin('admin u2', 'ca.reviewer_id = u2.id');

        if ($customerName) {
            $query->where('o.customer_name', 'like', '%' . $customerName . '%');
        }

        if ($status !== '') {
            $query->where('ca.archive_status', $status);
        }

        $total = $query->count();
        $list = $query->order('ca.create_time', 'desc')
            ->page($page, $limit)
            ->select();

        return $this->paginate($list ? $list->toArray() : [], $total, (int)$page, (int)$limit);
    }

    /**
     * 获取合同审核统计
     */
    public function stats()
    {
        // 待审核订单数
        $pendingOrders = Db::name('crm_order')
            ->alias('o')
            ->leftJoin('crm_contract_archive ca', 'o.id = ca.order_id')
            ->where('o.approval_status', 'in', [0, 1])
            ->where('ca.id', 'null')
            ->count();

        // 待归档数
        $pendingArchive = Db::name('crm_contract_archive')
            ->where('archive_status', 0)
            ->count();

        // 本月审核通过数
        $startOfMonth = strtotime(date('Y-m-01'));
        $thisMonthApproved = Db::name('crm_contract_archive')
            ->where('archive_status', 1)
            ->where('review_time', '>=', $startOfMonth)
            ->count();

        return $this->success([
            'pending_orders' => $pendingOrders,
            'pending_archive' => $pendingArchive,
            'this_month_approved' => $thisMonthApproved
        ]);
    }

    /**
     * 生成工单
     */
    private function generateWorkOrder($orderId)
    {
        $order = Db::name('crm_order')->find($orderId);
        if (!$order) {
            return false;
        }

        // 生成工单编号
        $workOrderNo = $this->generateWorkOrderNo();

        // 根据订单类型确定工单类别
        $category = 1;  // 默认案件委托工单
        if (in_array($order['order_sub_type'], [2, 3])) {
            $category = 2;  // 法务工单
        }

        $workOrderData = [
            'order_id' => $orderId,
            'work_order_no' => $workOrderNo,
            'category' => $category,
            'title' => '订单[' . $order['order_no'] . ']处理工单',
            'description' => '订单总金额：' . $order['total_amount'] . '元，已支付金额：' . $order['paid_amount'] . '元',
            'status' => 1,  // 待分配
            'priority' => 2,  // 中等
            'customer_id' => $order['customer_id'],
            'customer_name' => $order['customer_name'],
            'create_time' => time(),
            'update_time' => time()
        ];

        $workOrderId = Db::name('work_order')->insertGetId($workOrderData);

        if ($workOrderId) {
            // 记录工单创建进度
            Db::name('work_order_progress')->insert([
                'work_order_id' => $workOrderId,
                'operator_id' => 0,  // 系统操作
                'operator_name' => '系统',
                'progress_type' => 1,
                'new_status' => 1,
                'content' => '订单审核通过，工单已创建',
                'create_time' => time()
            ]);

            // 更新订单状态
            Db::name('crm_order')->where('id', $orderId)->update([
                'delivery_status' => 1,  // 交付中
                'approval_status' => 2,  // 审核通过
                'update_time' => time()
            ]);

            // 更新客户属性
            $this->calculateCustomerAttribute($order['customer_id']);
        }

        return $workOrderId;
    }

    /**
     * 生成工单编号
     */
    private function generateWorkOrderNo()
    {
        $prefix = 'WO';
        $date = date('Ymd');
        $lastOrder = Db::name('work_order')
            ->where('work_order_no', 'like', $prefix . $date . '%')
            ->order('id', 'desc')
            ->find();

        if ($lastOrder) {
            $lastNo = substr($lastOrder['work_order_no'], -6);
            $seq = str_pad($lastNo + 1, 6, '0', STR_PAD_LEFT);
        } else {
            $seq = '000001';
        }

        return $prefix . $date . $seq;
    }

    /**
     * 计算客户属性
     */
    private function calculateCustomerAttribute($customerId)
    {
        // 检查是否有案件委托订单
        $hasLawsuitOrder = Db::name('crm_order')
            ->where('customer_id', $customerId)
            ->where('order_sub_type', 1)
            ->where('approval_status', 2)
            ->count();

        // 检查是否有法务订单
        $hasLegalOrder = Db::name('crm_order')
            ->where('customer_id', $customerId)
            ->where('order_sub_type', 2)
            ->where('approval_status', 2)
            ->count();

        $attribute = 1;  // 默认为普通客户
        if ($hasLegalOrder > 0) {
            $attribute = 3;  // 会员客户
        } elseif ($hasLawsuitOrder > 0) {
            $attribute = 2;  // 合作客户
        }

        // 更新客户属性
        Db::name('crm_customer')->where('id', $customerId)->update([
            'customer_attribute' => $attribute,
            'update_time' => time()
        ]);

        return $attribute;
    }
}
